package service.outputDocument;

import model.Blocks;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class DataProcessor {
    private List titlePos;
    private Map paragraphPos;
    private Blocks blocks;

    /**
     *
     * @param blocks
     * @param contentPos
     */
    DataProcessor(Blocks blocks, List<Map> contentPos) {
        this.blocks=blocks;
        paragraphPos = new TreeMap();
        titlePos = new ArrayList();
        if (contentPos.size()==2){
            paragraphPos.putAll(contentPos.get(0));
            Map map = contentPos.get(1);
            titlePos.addAll(map.values());
        }else {
            titlePos=null;
            paragraphPos = new TreeMap();
            paragraphPos.putAll(contentPos.get(0));
        }
    }

    /**
     *
     * @return content
     */
    List<Map<Integer, String>> processData(){
        List<Map<Integer, String>> content = new ArrayList<Map<Integer, String>>();

        Map<Integer, String> title;
        if (!(titlePos==null)){
            title = spliceString(titlePos);
            content.add(title);
        }

        Map<Integer, String> paragraph;
        paragraph = spliceStringBetween(paragraphPos);
        content.add(paragraph);
        return content;
    }

    /**
     *
     * @param titlePos
     * @return title
     */
    private Map<Integer, String> spliceString(List titlePos){
        System.out.println("titlepos"+titlePos);

        Map<Integer, String> title = new TreeMap<Integer, String>();
        StringBuilder s =new StringBuilder();
//        for (Object p:titlePos){
//            System.out.println(p);
        int p = (Integer) titlePos.get(0);
        for (int i=0;i<p+1;i++){
            s.append(blocks.getTextBlocks().get(i).getContent());
        }
//        }
        title.put(0,s.toString());
        return title;
    }

    /**
     *
     * @param paragraphPos
     * @return pMap
     */
    private Map<Integer, String> spliceStringBetween (Map<Integer, Integer> paragraphPos){
        List<Integer> k = new ArrayList<Integer>();
        for (Object key:paragraphPos.keySet()){
            k.add((Integer) key);
        }
        List<Integer> v = new ArrayList<Integer>();
        System.out.println("K:"+k);

        for (Object values:paragraphPos.values()){
            v.add((Integer) values);
        }
        System.out.println("V:"+v);
        Map<Integer, String> pMap = new TreeMap<Integer, String>();
        for (int i=0;i<k.size();i++){
            int start = k.get(i);
            int end = v.get(i);
            StringBuilder s =new StringBuilder();
            for (int j=start;j<=end;j++){
                s.append(blocks.getTextBlocks().get(j).getContent());
            }
            pMap.put(i,s.toString());
        }
        System.out.println("pMap"+pMap);
        return pMap;
    }
}

